package tw.cating.Utility;

import java.util.Calendar;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DBUtil extends SQLiteOpenHelper{
	private static final String DATABASE_NAME = "nullbrain.db";
    private static final int DATABASE_VERSION = 2;
    
    private static final String TABLE_LOG = "log";
    
    private static final String ROW_PRIMARYKEY = "id";
    private static final String ROW_LOGTAG = "tag";
    private static final String ROW_TIMESTAMP = "time";
    private static final String ROW_LOGSEVERITY = "severity";
    private static final String ROW_CONTENT = "content";
    
    public DBUtil(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);
		// TODO Auto-generated constructor stub
	}
    
    public DBUtil(Context context) {
    	super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    
	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		String GenTable = "create table " + TABLE_LOG + " ( "
        + ROW_PRIMARYKEY + " integer primary key autoincrement, "
        + ROW_LOGTAG + " text not null, "
        + ROW_TIMESTAMP + " text, "
        + ROW_LOGSEVERITY + " integer, "
        + ROW_CONTENT + " text not null);";
		
		db.execSQL(GenTable);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
		for (int i = oldVersion; i < newVersion; i++) {
			switch (i) {
			case 1:
				String upgrade = "ALTER TABLE " + TABLE_LOG + " ADD " + ROW_TIMESTAMP + " text";
				db.execSQL(upgrade);
				break;
			default:
				break;
			}
		}
		
	}
	
	public void writeLog(String tag, int severity, String content) {
		SQLiteDatabase db = this.getWritableDatabase();
		
		ContentValues values = new ContentValues();
		values.put(ROW_LOGTAG, tag);
		values.put(ROW_LOGSEVERITY, severity);
		values.put(ROW_CONTENT, content);
		values.put(ROW_TIMESTAMP, StringUtil.Calendar(Calendar.getInstance()));
		db.insert(TABLE_LOG, null, values);
	}

}
